#!/bin/sh
#
# Configure the Annapurna
#
#

BNINET_HOME=/home/bninet
SQL_DIR=$BNINET_HOME/bni/sql

usage()
{
	echo "Usage: configure_annapurna <SRM_IP_ADDRESS> <SIMULATOR_IP_ADDRESS> <MGMT_SVCS_IP_ADDRESS> <VERBOSE-if-specified>"
	echo "    Example: configure_annapurna 10.10.12.29 10.10.12.225 10.10.12.20"
}

configure_database()
{
	echo "Configure the Annapurna database..."
	
  # initialize the database

	cat >tmp.sql <<EOF
use Topology;
set @SIMTYPE := "'EDGE', 'UDB', 'CEMP', 'SS', 'ADS', 'POIS', 'DW'";
-- Update the srm host
set @DI_SM_STAT = concat("
UPDATE DEVICE_INTERFACE SET ENDPOINT_REFERENCE = replace(ENDPOINT_REFERENCE, 'localhost:', '$SRM_IP_ADDRESS:') where DEVICE_ID in ( 
select b.DEVICE_ID 
from BASE_DEVICE b, DEVICE_TYPE d
where d.DEVICE_TYPE_NAME NOT in (", @SIMTYPE, ")
and b.DEVICE_TYPE_ID = d.DEVICE_TYPE_ID
)");

-- Update the simulator host
set @DI_SIM_STAT = concat("
UPDATE DEVICE_INTERFACE SET ENDPOINT_REFERENCE = replace(replace(ENDPOINT_REFERENCE, ':8180', ':8080'), 'localhost', '$SIMULATOR_IP_ADDRESS') where DEVICE_ID in (
select b.DEVICE_ID
from BASE_DEVICE b, DEVICE_TYPE d
where d.DEVICE_TYPE_NAME in (", @SIMTYPE, ")
-- where d.DEVICE_TYPE_NAME in ('EDGE', 'UDB', 'CEMP', 'SS')
and b.DEVICE_TYPE_ID = d.DEVICE_TYPE_ID
)");

-- Update the IP address
set @BD_SM_STAT = concat("
UPDATE BASE_DEVICE SET DEVICE_ADDRESS='$SRM_IP_ADDRESS' WHERE DEVICE_TYPE_ID IN ( 
select DEVICE_TYPE_ID from DEVICE_TYPE 
where DEVICE_TYPE_NAME NOT in (", @SIMTYPE, ")
)");

set @BD_SIM_STAT = concat("
UPDATE BASE_DEVICE SET DEVICE_ADDRESS='$SIMULATOR_IP_ADDRESS' WHERE DEVICE_TYPE_ID in (
select DEVICE_TYPE_ID from DEVICE_TYPE 
where DEVICE_TYPE_NAME in (", @SIMTYPE, ")
)");

-- execute the statement
PREPARE DI_SM_EX from @DI_SM_STAT;
PREPARE DI_SIM_EX from @DI_SIM_STAT;
PREPARE BD_SM_EX from @BD_SM_STAT;
PREPARE BD_SIM_EX from @BD_SIM_STAT;

EXECUTE DI_SM_EX;
EXECUTE DI_SIM_EX;
EXECUTE BD_SM_EX;
EXECUTE BD_SIM_EX;

-- Update the port
UPDATE BASE_DEVICE SET DEVICE_CONTROL_PORT='8080' WHERE DEVICE_CONTROL_PORT ='8180';
EOF
	mysql -h $MGMT_SVCS_IP_ADDRESS --user=user --password=password --database=Topology < tmp.sql
	rm -f tmp.sql
	echo "Done Configure the Annapurna database."
}

#MAIN
if [ $# -ne 3 ]
then
  	usage
  	exit 1
else
	SRM_IP_ADDRESS=$1
	SIMULATOR_IP_ADDRESS=$2
  MGMT_SVCS_IP_ADDRESS=$3
fi

configure_database

